package com.futvan.z.erp.crm_customer_ticket;

import com.futvan.z.erp.customer.CustomerService;
import com.futvan.z.erp.customer.crm_customer;
import com.futvan.z.erp.customer.crm_customer_address;
import com.futvan.z.erp.erp_account.erp_account;
import com.futvan.z.erp.zproduct.ZproductService;
import com.futvan.z.erp.zproduct.z_product;
import com.futvan.z.erp.zstorehouse.ZstorehouseService;
import com.futvan.z.erp.zstorehouse.z_storehouse;
import com.futvan.z.erp.zstorehouse.z_storehouse_area;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.common.service.CommonService;
import com.futvan.z.framework.core.SuperAction;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.DateUtil;
import com.futvan.z.framework.util.FileUtil;
import com.futvan.z.framework.util.HttpUtil;
import com.futvan.z.framework.util.TicketExcelUtil;
import com.futvan.z.shop.order.OrderService;
import com.futvan.z.shop.order.s_order;
import com.futvan.z.shop.order.s_order_products;
import com.futvan.z.shop.sticket.SticketService;
import com.futvan.z.shop.sticket.s_ticket;
import com.futvan.z.shop.sticket.s_ticket_product;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class Crm_customer_ticketTicketGrantButtonAction extends SuperAction {
    @Resource
    private CustomerService customerService;
    @Resource
    private Crm_customer_ticketService crm_customer_ticketService;
    @Resource
    private SticketService sticketService;
    @Resource
    private ZproductService zproductService;
    @Resource
    private OrderService orderService;
    @Resource
    private ZstorehouseService zstorehouseService;

    @RequestMapping(value = "/ticketGrant")
    public @ResponseBody
    Result ticketGrant(@RequestParam HashMap<String, String> bean) throws Exception {
        String zids = bean.get("zids");
        String[] zidArray = zids.split(",");

        //转订单
        //setOrder(zidArray);

        return Result.success(zidArray.length);
    }

    @RequestMapping(value = "/resolve")
    public @ResponseBody
    Result resolveTicket(@RequestParam HashMap<String, String> bean) throws Exception {
        String url = bean.get("url");
        //下载到本地
        String path = HttpUtil.download(url, System.getProperty(z.sp.get("tempfiles")) + "/temp/importExcel", "ticketExcel");
        //解析excel
        List<excel_ticket> ticketExcel = TicketExcelUtil.parseFromExcel(path, 1, excel_ticket.class);

        boolean canSend = false;

        //验证信息有效性
        if (z.isNotNull(ticketExcel)) {
            for (int i = 0; i < ticketExcel.size(); i++) {
                StringBuffer stringBuffer = new StringBuffer();
                //验证客户有效性
                crm_customer customerInfo = customerService.getCustomerInfo(ticketExcel.get(i).getCustomid());
                if (z.isNull(customerInfo)) {
                    canSend = true;
                    stringBuffer.append("用户不存在");
                }
                //验证赠品券有效性
                s_ticket ticketInfo = sticketService.getTicketInfo(ticketExcel.get(i).getTicket());
                if (z.isNull(ticketInfo)) {
                    canSend = true;
                    stringBuffer.append("赠品券不存在");
                }

                ticketExcel.get(i).setCustomid(ticketExcel.get(i).getCustomid());
                ticketExcel.get(i).setTicket(ticketExcel.get(i).getTicket());
                ticketExcel.get(i).setErrorMsg(stringBuffer.toString());
                ticketExcel.get(i).setAddress(ticketExcel.get(i).getAddress());
                ticketExcel.get(i).setCount(ticketExcel.get(i).getCount());
                ticketExcel.get(i).setRelation_order(ticketExcel.get(i).getRelation_order());
            }
        }

        //判断错误列表是否有数据，有则返回
        if (canSend) {
            //将错误数据生成excel
            String errorPath = TicketExcelUtil.writeExcelWithTitle(ticketExcel, System.getProperty(z.sp.get("tempfiles")) + "/temp/errorExcel.xls");
            //excel上传到文件服务器
            File excelFile = new File(errorPath);
            String errorTicketExcel = FileUtil.UploadFile("errorTicketExcel.xls", new FileInputStream(excelFile));
            return Result.error("上传失败", errorTicketExcel);
        }
        //插入到赠品券列表
        for (int i = 0; i < ticketExcel.size(); i++) {
            for (int j = 0; j < ticketExcel.get(i).getCount(); j++) {
                ticketInsert(ticketExcel.get(i));
            }
        }

        //将赠品券转为订单
        setOrder(ticketExcel);

        return Result.success();
    }


    /**
     * 执行插入列表操纵
     *
     * @param importTicket
     */
    public void ticketInsert(excel_ticket importTicket) {
        crm_customer_ticket ticket = new crm_customer_ticket();
        ticket.setCustomid(importTicket.getCustomid());
        ticket.setIs_use("1");
        ticket.setTicket(importTicket.getTicket());
        ticket.setAddress(importTicket.getAddress());
        ticket.setRelated_order(importTicket.getRelation_order());
        ticket.setZid(z.newZid());
        ticket.setEndtime(DateUtil.getDateTime());

        crm_customer_ticketService.insertTicket(ticket);
    }


    /**
     * 遍历赠品券，将产品转成订单
     *
     * @throws Exception
     */
    public void setOrder(List<excel_ticket> list) throws Exception {
        s_order o = new s_order();

        for (int i = 0; i < list.size(); i++) {
            String zid = list.get(i).getTicket();
            //获取用户信息
            crm_customer customerInfo = customerService.getCustomerInfo(list.get(i).getCustomid());

            //买家
            o.setBuyer_id(customerInfo.getZid());
            o.setBuyer_name(customerInfo.getNickname());
            o.setBuyer_tel(customerInfo.getTel());

            //生成订单编号与主键  = 买家小组号+随机数
            String czid = z.newNumber("PS" + customerInfo.getGroup_num(), "yyyyMMdd", 6);
            o.setZid(czid);//主健
            o.setNumber(czid);//编号
            o.setCreate_time(DateUtil.getDateTime());//创建时间
            o.setPay_time(DateUtil.getDateTime());//创建付款时间

            //卖家：如果买家是经销商，默认卖家就是自己
            if ("1".equals(customerInfo.getLevel()) || "经销商".equals(customerInfo.getLevel())) {
                o.setSeller_id(customerInfo.getZid());
                o.setSeller_name(customerInfo.getNickname());
            } else {
                //获取根据买家获取卖家
                crm_customer seller = customerService.getCustomerInfo(customerInfo.getParentid());
                o.setSeller_id(seller.getZid());
                o.setSeller_name(seller.getNickname());
            }

            //小组
            o.setGroup_num(customerInfo.getGroup_num());

            //下单人
            o.setCreate_order_customer(customerInfo.getZid());
            //关联订单
            o.setOther_order_zid(list.get(i).getRelation_order());

            //状态
            o.setOrder_status("10");

            //默认仓库
            if(z.isNotNull(zstorehouseService.checkStore(list.get(i).getStartStorehouse()))){
                o.setStart_storehouse(zstorehouseService.checkStore(list.get(i).getStartStorehouse()));
            }
            // 验证地址有效性
//            crm_customer_address address = customerService.getAddrewss(list.get(i).getAddress().trim());
//            if (z.isNull(address)) {
//                list.get(i).getAddress().substring(0,2);
//            } else {
//                //默认仓库
//                o.setStart_storehouse(getStartStorehouse(address));
//            }

//            //默认仓库
//            if (z.isNull(customerService.getCustomerDefaultAddress(customerInfo.getZid()))) {
//                o.setStart_storehouse("");
//            } else {
//                o.setStart_storehouse(customerService.getCustomerDefaultAddress(customerInfo.getZid()).getAreaid());
//            }

            //配送公司
            o.setCourier_company(z.sp.get("shop_express_company"));

            o.setCustom_address(list.get(i).getCustomid());
            //完整地址
            o.setCustom_eaddress_complete(list.get(i).getAddress());

          //  crm_customer_address cca = customerService.getCustomerDefaultAddress(customerInfo.getZid());
//            cca.setAllinfo(list.get(i).getAddress());
//            //地址
//            if (z.isNotNull(cca)) {
//
//                o.setObj(cca);
//            }


            //客户电话
            o.setCustomer_service_tel(z.sp.get("shop_customer_service_tel"));

            //产品总额
            BigDecimal product_total = new BigDecimal(0);

            //PV总额
            BigDecimal pv_total = new BigDecimal(0);

            Map map = new HashMap();

            //产品明细
            List<s_order_products> oplist = new ArrayList<s_order_products>();


            //赠品券信息
            s_ticket ticketInfo = sticketService.getTicketInfo(list.get(i).getTicket());
            //赠品券关联产品列表
            List<s_ticket_product> ticketProductList = sticketService.getTicketProductList(ticketInfo.getZid());

            for (s_ticket_product stp : ticketProductList) {
                z_product productInfo = zproductService.getProductInfo(stp.getProductid());
                //构建订单产品明细表对象
                s_order_products op = new s_order_products();
                //主键
                op.setZid(z.newZid());
                //外键
                op.setPid(czid);
                //产品ID
                op.setProduct(stp.getProductid());

                //是否赠品
                op.setIs_gift("1");

                //单价
                op.setPrice(productInfo.getPrice_retail());
                op.setPrice("0");
                //金额 = 数量 * 零售价
                //
                BigDecimal count = new BigDecimal(stp.getAmount());
                BigDecimal countlist = new BigDecimal(list.get(i).getCount());

                BigDecimal multiply = count.multiply(countlist);

                //数量
                op.setAmount(multiply.toString());

                BigDecimal price = new BigDecimal(productInfo.getPrice_retail());
                BigDecimal pv = new BigDecimal(productInfo.getPv());

                BigDecimal total = multiply.multiply(price);
                op.setTotal(total.toString());
                op.setTotal("0");
                //批次+发送U8时获取有效批次信息
                //op.setBatchid(getProductBatchId(p.getZid()));

                //PV总额 = 数量 * PV单价
                BigDecimal pvtotal = multiply.multiply(pv);

                //设置产品对象到obj
                op.setObj(productInfo);
                //总额
                product_total = product_total.add(total);

                //PV总额
                pv_total = pv_total.add(pvtotal);

                //加入订单明细对象
                oplist.add(op);
            }

            map.put("oplist", oplist);
            o.setDetails(map);

            //产品总额
            o.setProduct_total(product_total.toString());
            o.setProduct_total("0");

            //PV总额
            o.setPv_total(pv_total.toString());
            o.setPv_total("0");
            //包邮
            o.setFreight("0");

            o.setEquipment_type("pc");

            //合计金额
            o.setTotal(product_total.toString());
            o.setTotal("0");

            //保存订单
            orderService.insertProduct(o);
        }
    }

    /**
     * 根据收货地址，获取发货仓库
     *
     * @return
     */
    public String getStartStorehouse(crm_customer_address address) {
        String default_storehouse_id = "";
        //判读收货ID是否为空
        if (z.isNotNull(address)) {
            //判读收货ID是否有效
            if (z.isNotNull(address)) {
                //获取收货地址对应省份
                String areaid = address.getAreaid().substring(0, 2) + "0000";
                //根据省份找到对应发货仓库ID
                z_storehouse_area sa = zstorehouseService.getStoreArea(areaid);
                if (z.isNotNull(sa)) {
                    default_storehouse_id = sa.getPid();
                } else {
                    default_storehouse_id = getDefaultStoreHouseId();
                }
            } else {
                default_storehouse_id = getDefaultStoreHouseId();
            }
        } else {
            default_storehouse_id = getDefaultStoreHouseId();
        }
        return default_storehouse_id;
    }

    /**
     * 获取默认发货仓库ID
     *
     * @return
     */
    private String getDefaultStoreHouseId() {
        return zstorehouseService.getString();
    }
}